package com.david.andserver.util;

import android.os.Environment;
import android.text.TextUtils;

import com.david.andserver.NetInfo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 夸克绝对路径转相对路径,只针对m3u8，使andserver部署之后能正常访问m3u8的视频资源。
 * 在单独的文件夹中添加链接到夸克或UC视频的链接
 */
public class PathUtil {

    public static void main(String[] args) {

        System.out.println("/storage/emulated/0/Quark/Download/eda5e14f7bc868ebdb02dbe9b9db794855774243/Y2hlbmppbmdjb25n0".indexOf("Quark/Download"));
//        checkFiles("C:\\Users\\weixi\\Downloads");
    }
    public static final String QURK_DOWN_PATH = "/Quark/Download";

    public static String QURK_VIDEO_STRING = "";
    public static String getQurkNetVideoData(){
        if (TextUtils.isEmpty(QURK_VIDEO_STRING)) {

            File resultDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/downvideos");
            if (resultDir.exists()) {
                StringBuilder stringBuilder = new StringBuilder();
                File[] items = resultDir.listFiles();

                if (items == null || items.length == 0) {
                    return QURK_VIDEO_STRING;
                }

                stringBuilder.append("{\"size\":").append(items.length).append(",\"data\":[");

                for (File item: items) {
                    stringBuilder.append("{\"title\":\"")
                            .append(item.getName())
                            .append("\",\"url\":\"")
                            .append("http://")
                            .append(NetInfo.ip)
                            .append( ":8080/downvideos/")
                            .append(item.getName()).append("\"},");

                }

                String result = stringBuilder.toString();
                QURK_VIDEO_STRING = result.substring(0, result.length() - 1) + "]}";
            }
        }

        return QURK_VIDEO_STRING;

    }

    /**
     * 生成的链接单独放到downvideo文件夹中
     */
    public static void createNetLinks(){
        String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File( storagePath + "/Quark/Download");
        File[] listFile = file.listFiles();
        File resultDir = new File(storagePath + "/downvideos");
        if (!resultDir.exists()) {
            resultDir.mkdirs();
        }
        File result;
        for (File item : listFile) {
            if (item.isDirectory()) {
                continue;
            } else if (item.getAbsolutePath().endsWith(".m3u8") && !(result = new File(storagePath + "/downvideos/" + item.getName())).exists()) {
                try {
                    BufferedReader reader = new BufferedReader(new FileReader(item));
                    String line = null;
                    BufferedWriter writer = new BufferedWriter(new FileWriter(result));
                    while ((line = reader.readLine()) != null) {
                        if (line.contains(QURK_DOWN_PATH)) {
                            if (line.contains("#EXT-X-KEY:METHOD=")) {
                                String[] ss = line.split("\"");
                                StringBuilder builder = new StringBuilder();
                                for (int i = 0; i < ss.length; ++i) {
                                    if (ss[i].contains(".key")) {
                                        builder.append("\"../Quark/Download").append(ss[i].split("Quark/Download")[1]).append("\"");
                                    } else {
                                        builder.append(ss[i]);
                                    }
                                }

                                writer.write(builder.toString() + "\n");
                            } else {
                                writer.write(".."+line.substring(line.indexOf("/Quark/Download")) + "\n");
                            }
                        } else {
                            writer.write(line+"\n");
                        }
                    }
                    reader.close();
                    writer.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void checkFiles(String dirPath){
        checkFiles(new File(dirPath));
    }

    public static void checkFiles(File dir){
        if (!dir.isDirectory()) {
            return;
        }
        File[] list = dir.listFiles();
        for(File item:list){
            if (!item.isDirectory() && !item.getAbsolutePath().contains("net_") && item.getAbsolutePath().contains(".m3u8")) {
                if (new File(dir.getAbsolutePath() + "net_" + item.getName()).exists()) {
                    continue;
                }

                createNetFile(dir, item);
            }
        }
    }

    private static void createNetFile(File dir, File item) {
        File netFile = new File(dir.getAbsolutePath()+"/net_" +item.getName());
        try {
//            netFile.createNewFile();
            BufferedReader reader = new BufferedReader(new FileReader(item));
            String line = null;
            BufferedWriter writer = new BufferedWriter(new FileWriter(netFile));
            while ((line = reader.readLine()) != null) {
                if (line.contains(QURK_DOWN_PATH)) {
                    writer.write("." + line.substring(line.indexOf(QURK_DOWN_PATH) + 15) + "\n");
                } else {
                    writer.write(line+"\n");
                }
            }
            reader.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}